from jinja2 import Environment, FileSystemLoader
import os.path
import time
import json

"""
jinja2模板;修改log模板输出;
"""


def log(*args, **kwargs):
    # time.time() 返回 unix time
    # 如何把 unix time 转换为普通人类可以看懂的格式呢？
    format = '%H:%M:%S'
    value = time.localtime(int(time.time()))
    dt = time.strftime(format, value)
    with open('log.gua.txt', 'a', encoding='utf-8') as f:
        print(dt, *args, file=f, **kwargs)


# __file__ 就是本文件的名字
# 得到用于加载模板的目录
path = '{}/templates/'.format(os.path.dirname(__file__))
# log('path, ', path)
# 创建一个加载器, jinja2 会从这个目录中加载模板
loader = FileSystemLoader(path)
# 用加载器创建一个环境, 有了它才能读取模板文件
env = Environment(loader=loader)


# 调用 get_template() 方法加载模板并返回
def template(path, **kwargs):
    t = env.get_template(path)
    return t.render(**kwargs)


def response_with_headers(headers, code=200):
    header = 'HTTP/1.1 {} VERY OK\r\n'.format(code)
    header += ''.join(['{}:{}\r\n'.format(k, v)
                       for k, v in headers.items()])
    return header


def redirect(location):
    headers = {
        'Content-Type': 'text/html',
    }
    headers['Location'] = location
    header = response_with_headers(headers, 302)
    r = header + '\r\n' + ''
    return r.encode(encoding='utf-8')


"""
ctrl+shift+N:
"""


def http_response(body, headers=None):
    header = 'HTTP/1.1 200 OK\r\nContext-Type: text/html\r\n'
    if headers is not None:
        header += ''.join(['{}: {}\r\n'.format(k, v)
                           for k, v in headers.items()])
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')


def error(code=404):
    e = {
        404: b'HTTP/1.x 404 Not FOUND\r\n\r\n<h1>NOT FOUND</h1> ',
    }
    return e.get(code, b'')


def json_response(data):
    header = 'HTTP/1.1 200 OK\r\nContent-Type:application/json\r\n'
    body = json.dumps(data, ensure_ascii=False, indent=2)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')

"""
测试：已有文件，修改，提交
"""